const WXAPI = require('apifm-wxapi')

Page({
    data: {
      formData:{
        itemTitle: '',
        sellPoint: '',
        shareContent: '',
        price:'',
        stockNum: ''
      },
      fileList: [],
      catList: [],
      catNo:'',
      catAllList: [],
      defaultCat : '',
      type: 'create',
      itemNo: ''

      
    },
  catChange(event) {
    const { picker, value, index } = event.detail;
    const cat = this.data.catAllList[index].catNo
    this.setData({
      catNo: cat
    })
  },
  onLoad(options){
    console.log(options)
    const { id, type} = options
    if(id){
      WXAPI.goodsInfo(id).then((res) => {
        console.log(res, this.data)
        if(res.retCode === '200'){
          const dataMap = res.data
          const {itemTitle, price, sellPoint, shareContent, stockNum } = dataMap
          const temp = {itemTitle, price, sellPoint, shareContent, stockNum }
  
          this.setData({
            catNo: dataMap.catNo,
            formData: temp,
            itemNo: id,
            type: 'edit',
            fileList: dataMap.itemPicResultDtos.map((item) => {
              return {
                ...item,
                url: item.picUrl,
                isImage: true
              }
            })
          })
        }
      })
    }else{
      this.setData({
        type: 'create'
      })
    }
    
  },
  onShow(options){
    console.log(options)
    that.findAllCatFun();
  },
  findAllCatFun(){
    var that = this;
    if (app.globalData.shopNo && app.globalData.shopNo != '') {
      WXAPI.findAllCat().then((res) => {
        if (res.retCode === '200') {

          if (this.data.catNo) {
            let temp = 0
            res.data.forEach((item, index) => {
              if (item.catNo === this.data.catNo) {
                temp = index
              }
            })
            this.setData({
              defaultCat: temp
            })
          }
          this.setData({
            catAllList: res.data,
            catList: res.data.map(item => item.catName),
            catNo: res.data[0].catNo
          })
        } else {
          this.setData({
            catList: []
          })
        }
      })
    } else {
      setTimeout(function () {
        that.findAllCatFun()
      }, 300)
    }
  },
    onChange(event) {
      // event.detail 为当前输入的值
      
      const { id } = event.target
      const { detail } = event
      const { itemTitle, sellPoint, shareContent, price, stockNum} = this.data.formData
      this.setData({
        formData:{
          itemTitle: id === 'itemTitle' ? detail : itemTitle,
          sellPoint: id === 'sellPoint' ? detail : sellPoint,
          shareContent: id === 'shareContent' ? detail : shareContent,
          price: id === 'price' ? detail : price,
          stockNum: id === 'stockNum' ? detail : stockNum,
        }
      })
    },
    afterRead(event) {
      const { file } = event.detail;
      const _this = this
      // console.log(file)
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      file.forEach((item,index) => {
        wx.uploadFile({
          // url: 'http://106.15.237.241:8081/common/file/uploadFile',
          url: 'https://jinfang.xunyu.shop/common/file/uploadFile',
          filePath: item.path,
          name: 'file',
          formData: { user: 'test' },
          success(res) {
            const dataMap = res.data
            dataMap && JSON.parse(dataMap) && JSON.parse(dataMap).data && _this.getFile(file[index], JSON.parse(dataMap).data)
          },
          fail(res) {
            wx.showToast({
              title: res,
            })
          }
        });
      })
    },
  submit(){
    console.log(this.data)
    const { formData, catNo, type } = this.data
    const picList = this.data.fileList.map((item, index) => {
      return {
        narrowPicNo: item.narrowPicNo || item.narrowPicUrl.split('/')[item.narrowPicUrl.split('/').length - 1],
        picNo: item.fileNo || item.picUrl.split('/')[item.picUrl.split('/').length - 1],
        isMain: index < 2 ? '1' : '0'
      }
    })
    const postData = {
      ...formData,
      picList,
      catNo

    }
    if(type === 'edit'){
      this.editGoods(postData)
    }else{
      this.createGoods(postData)
    }

  },
  editGoods(postData){
    const params = {...postData, itemNo: this.data.itemNo}
    WXAPI.modiGoods(params).then((res) => {
      if (res.retCode === '200'){
        wx.showModal({
          title: '提示',
          content: '修改成功',
          showCancel: false,
          confirmText: '查看',
          success(res) {
            wx.redirectTo({
              url: "/pages/goods-manage/index"
            })
          }
        })
      }else{
        wx.showToast({
          icon:'none',
          title: res.retMsg
        })
      }
    })
  },
  deletPic(e){
    const { index } = e.detail
    console.log(index)
    const tempArr = [...this.data.fileList]
    tempArr.splice(index, 1)
    this.setData({
      fileList: tempArr
    })
  },
  createGoods(postData){
    WXAPI.addGoods(postData).then((res) => {
      if (res.retCode === '200'){
        wx.showModal({
          title: '提示',
          content: '创建成功',
          cancelText: '查看商品',
          confirmText: '继续创建',
          success(res) {
            if (res.confirm) {
              const pages = getCurrentPages()
              //声明一个pages使用getCurrentPages方法
              const perpage = pages[pages.length - 1]
              //声明一个当前页面
              perpage.onLoad()
            } else {
              wx.redirectTo({
                url: "/pages/goods-manage/index"
              })
              
            }
          }
        })
      }else{
        wx.showToast({
          icon:'none',
          title: res.retMsg
        })
      }
    })
  },
    getFile(file, fileParams){
      // 上传完成需要更新 fileList
      const { fileNo, narrowFileNo} =  fileParams
      const { fileList = [] } = this.data;
      const fileList1 = fileList.concat(([{ ...file, narrowPicNo: narrowFileNo, fileNo,url: `https://yixuanshow.top/common/file/findByNo/${fileNo}` }]));
      this.setData({
        fileList: fileList1
      })
    }
  })